package com.mykt.aspect;

import com.mykt.annotation.MyInnerAuth;
import com.mykt.constant.SecurityConstants;
import com.mykt.exception.MyServiceException;
import com.mykt.utils.StringUtils;
import com.mykt.utils.servlet.ServletUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 内部服务调用验证处理
 */
@Aspect
@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE + 1) //确保在权限认证aop执行前执行
public class MyInnerAuthAspect
{
    @Around("@annotation(innerAuth)")
    public Object innerAround(ProceedingJoinPoint point, MyInnerAuth innerAuth) throws Throwable {
        String source = ServletUtils.getHeaderParameter(SecurityConstants.FROM_SOURCE);

        //校验head参数中的from-source 是否为 inner 内部请求
        if (!StringUtils.equals(SecurityConstants.INNER, source)) {
            throw new MyServiceException("没有内部访问权限，不允许访问");
        }

        String userId = ServletUtils.getHeaderParameter(SecurityConstants.DETAILS_USER_ID);
        String userName = ServletUtils.getHeaderParameter(SecurityConstants.DETAILS_USERNAME);
        // 用户信息验证
        if (innerAuth.isUser() && (StringUtils.isEmpty(userId) || StringUtils.isEmpty(userName))) {
            throw new MyServiceException("没有设置用户信息，不允许访问");
        }
        return point.proceed();
    }

}
